<script setup lang='ts'>
import { reactive, computed } from 'vue';
import useFileStore, { FileState } from '@/store/file.ts';
import { storeToRefs } from 'pinia';
import wm from 'watermarkjs';
import { saveAs } from 'file-saver';
import JSZip from 'jszip';

// 掘金 >> 前端

const fileStore = useFileStore();

const file = storeToRefs(fileStore);

const options = reactive({
  opacity: .5,
  scale: 1,
  position: 'center',
});

// 下载
async function onDownload () {

  const zip = JSZip();

  await Promise.all(file.imageFileList.value.map((image: any, i: number) => {
    return new Promise(async (resolve) => {
      // 用watermark印水印
      const img = await wm([image, file.logoFile.value])
      .image(wm.image[options.position](options.opacity));

      // 把印好的东西扔到zip包中
      zip.file(`印好的(${ i + 1 }).png`, img.src.split(',')[1], { base64: true });
      resolve(null);
    });
  }));

  zip.generateAsync({ type: 'blob' })
    .then((blob) => {
      saveAs(blob, '印好的.zip');
    });

}

</script>

<template>
  <a-form
    :model="options"
    name="basic"
    autocomplete="off"
    @finish="onDownload"
  >
    <a-form-item
      label="透明度"
      name="opacity"
    >
      <a-slider v-model:value="options.opacity" :min="0" :max="1" />
    </a-form-item>

    <a-form-item
      label="缩放"
      name="scale"
    >
      <a-slider v-model:value="options.scale" :min=".1" :max="5" />
    </a-form-item>

    <a-form-item
      label="位置"
      name="position"
    >
      <a-radio-group v-model:value="options.position">
        <a-radio value="center">居中</a-radio>
        <a-radio value="lowerRight">右下</a-radio>
        <a-radio value="lowerLeft">左下</a-radio>
        <a-radio value="upperRight">右上</a-radio>
        <a-radio value="upperLeft">左上</a-radio>
      </a-radio-group>
    </a-form-item>

    <a-form-item>
      <a-button type="primary" html-type="submit">下载</a-button>
    </a-form-item>
  </a-form>
</template>

<style>

</style>